/**
 * 
 * @project : privateNotes
 * 
 * @file: subEdit.js
 * 
 * @author: appPro-01
 * 
 * @created_date : Saturday, April 20th 2019, 3:53:37 pm
 * --------------------------------------------------
 * @last_modified : appPro-01
 * @modified_by : Monday, April 29th 2019, 3:09:46 pm
 * 
 * --------------------------------------------------
 * 
 * MIT License
 * 
 * Copyright (c) 2019 appPro
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 * 
 * --------------------------------------------------
 * 
 * @fileoverview: `function describe / 功能描述`
 * 
 * @flow
 * 
 */

'use strict'

import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  DeviceEventEmitter,
  TouchableWithoutFeedback
} from 'react-native'

import Input         from '../../../components/textInput/input'
import FieldText     from '../../../components/textInput/filedText'

import SubEditBottom from './subEditBottom'

import RXJSON        from '../../../utils/Cache/file/RXJSON'
import RXEmitterAPI  from '../../../utils/RXEmitterAPI'
import RXPlatform    from '../../../utils/RXPlatform'

const BOTTOM = RXPlatform.ifIphoneX(20, 10, 10);

export default class SubEdit extends Component {

  static defaultProps = {
    style: {flex: 1},
  }

  constructor(props) {
    super(props);
    this.state = ({
      editing: false,
      defaultTitleValue: '',
      defaultContentValue: '',

      id: '',
      titleValue: '',
      contentValue: '',
      contentValueLength: 0,

      enable: false,
    })
  }

  componentDidMount() {
    let {navigation} = this.props;
    let state = navigation.state || {}
    let params = state.params || {}
    let id = params.id || 0

    if(id > 0) {
      this._readCache(id);
    }
  }

  componentWillUnmount() {
    this.blur;
  }

  blur() {
    if(this.refInput) {
      this.refInput.blur()
    }
    if(this.refFieldText) {
      this.refFieldText.blur()
    }
  }

  saveFile() {
    console.log('edit -> index.js -> doing write file ...')
    let titleValue = this.state.titleValue;
    let contentValue = this.state.contentValue;
    RXJSON.save(titleValue, contentValue, this.id, (flag, id)=>{
      if(!flag) {
        console.warn('write error subEdit->saveFile() flag=false')
        return;
      }
      id = id || 0
      if(!id) {
        console.warn('write error subEdit->saveFile() id=null')
        return;
      }
      if(!this.state.enable) {
        this.setState({enable: true})
      }
      this.id = id;
      //调用事件通知
      DeviceEventEmitter.emit(RXEmitterAPI.RXEA_edit_success, {id} );
    });
  }

  _readCache(id) {
    if(id < 1) return;
    RXJSON.getFileContentInCache(id, (result)=>{
       if(!result) return;
       let title = result[RXJSON.NOTE_TITLE_KEY] || '';
       let content = result[RXJSON.NOTE_CONTENT_KEY] || '';

      this.setState({
        id,
        enable: true,
        defaultTitleValue: title,
        defaultContentValue: content
      })
      
      this.state.titleValue = title;
      this.state.contentValue = content;
      this.contentValueChange(title, content);
    });
  }

  render(){
    return(
      <TouchableWithoutFeedback
        onPress={()=>{
            if(this.refFieldText) {
            this.refFieldText.focus()
            }
        }}
      >
      <View style={this.props.style}>
        <View style={styles.fieldTextView}>
          <Input 
            style={styles.fieldTextTitle}
            ref={refInput=>this.refInput=refInput} 
            defaultValue={this.state.defaultTitleValue}
            autoFocus={true}
            maxLength={24}
            placeholder={'输入标题'}
            onChangeText={(text) => { //当文本框内容变化时调用此回调函数。
              this.state.titleValue = text;
              this.contentValueChange();
            }} 
          />
          <View style={styles.line} />
          <FieldText
            style={styles.fieldTextContent}
            ref={refFieldText=>this.refFieldText=refFieldText} 
            defaultValue={this.state.defaultContentValue}
            placeholder={'输入内容'}
            onChangeText={(text) => { //当文本框内容变化时调用此回调函数。
              this.state.contentValue = text
              this.contentValueChange();
            }} 
          />
        </View>
        <SubEditBottom style={styles.bottom}
          //属性
          id={this.state.id}
          editing={this.state.editing}
          enable={this.state.enable}
          //方法
          callSaveFun={()=>this.saveFile()}
        />
      </View>
      </TouchableWithoutFeedback>
    )
  }

  contentValueChange(title, content) {
    var editing = false;
    let defaultTitleValue = this.state.defaultTitleValue;
    let defaultContentValue = this.state.defaultContentValue;

    let titleValue = title?title:this.state.titleValue;
    let contentValue = content?content:this.state.contentValue;

    if(defaultContentValue != contentValue) {
      editing = true;
    }

    this.setState({editing})

    let contentValueLength = contentValue.length;
    if(this.props.callBack) {
      this.props.callBack(editing, contentValueLength, titleValue, contentValue);
    }
  }

}

const styles = StyleSheet.create({
  fieldTextView: {
    flex: 1,
    padding: 10,
    marginTop: 10,
    borderRadius: 10, 
    borderWidth: 2,
    borderColor: '#1E90FF',
    backgroundColor: 'white',
  },

  fieldTextTitle: {
    height: 30,
    fontSize: 16,
    lineHeight: 20,
    paddingTop: 10,
    fontWeight: 'bold',
  },

  line: {
    marginTop: 10,
    marginBottom: 10,
    height: 1,
    backgroundColor: '#eee'
  },

  fieldTextContent: {
    flex: 1,
    fontSize: 14,
    lineHeight: 16,
  },

  bottom: {
    marginTop: 10,
    marginBottom: BOTTOM,
  },
  
})





